package com.zito.health.config;

import com.zito.health.core.util.EncodesUtil;
import com.zito.health.entity.User;
import com.zito.health.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

/**
 * @description:
 * @author: gxt
 * @time: 2019/10/12 11:09
 */
public class SecurityRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        /*for (SysRole role : user.getRoleList()) {
            authorizationInfo.addRole(role.getRole());
            for (SysPermission p : role.getPermissions()) {
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }*/
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();

//        User user = userService.queryByUsername(username);
        User userParam = new User();
        userParam.setUsername(username);
        User user = userService.queryOne(userParam);
        if (user == null) {
            return null;
        }
        if (user.getEnabled() == 2) { //账户冻结
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                new Principal(user), //用户名
                user.getPassword(), //密码
                null,
                getName()
        );
        return authenticationInfo;

    }

    /**
     * 授权用户信息
     */
    public static class Principal implements Serializable {

        private static final long serialVersionUID = 1L;

        private String id; // 编号
        private String name; // 姓名

        public Principal(User user) {
            this.id = String.valueOf(user.getUserid());
            this.name = user.getUsername();
        }

        public String getId() {
            return id;
        }


        public String getName() {
            return name;
        }

    }
}
